<template>
	<div class="login-container">
		<el-form :model="formData" :rules="formRules" ref="loginForm" label-width="80px" class="login-form">
			<el-form-item>
				<h1 class="title">小布的店铺</h1>
			</el-form-item>
			<el-form-item label="用户名" prop="usercode">
				<el-input v-model="formData.usercode"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input type="password" v-model="formData.password"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleLogin">登录</el-button>
       <el-button type="primary" @click="toRegister" >注册</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
  import userApi from "@/api/user/user_api";
	export default {
		name: "login",
		data() {
			return {
        formData: {
          usercode: '',
					password: ''
				},
        formRules: {
					usercode: [{
						required: true,
						message: '请输入用户名',
						trigger: 'blur'
					}],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					}]
				}
			}
		},
		methods: {
			handleLogin() {
        localStorage.setItem("token",'')
				this.$refs.loginForm.validate((valid) => {
					if (valid) {
            userApi.login(this.formData).then(res=>{
              this.$message.success("登录成功")
              let token=res.data.data.token
              let user=res.data.data.user
              localStorage.setItem("token", token)
              localStorage.setItem("user", JSON.parse(user))
              this.$router.push('/product')
            }).catch(error => {
              this.$message.error(error)
            });

					} else {
						return false
					}
				})
			},
      toRegister(){
        this.$router.push('/register')
      }
		}
	}
</script>

<style scoped>
	.login-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;

	}

	.login-form {
		width: 400px;
		margin: 50px;
	}

	.title {
		font-size: 24px;
		font-weight: bold;
		margin-left: 16px;
	}
</style>
